package com.aw.baselib.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.aw.baselib.R;
import com.aw.baselib.util.AwDataUtil;
import com.aw.baselib.util.AwLog;
import com.aw.baselib.util.AwToastUtil;
import com.aw.baselib.widgets.AwViewCustomToolbar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by hzw
 */

public abstract class AwBaseFragment extends Fragment implements AwBaseView, View.OnClickListener {

    protected AwBaseActivity mActivity;
    protected CompositeDisposable mCompositeSubscription;
    protected String TAG = "";
    protected View view;
    protected AwViewCustomToolbar mToolbar;
    protected FragmentManager mFragmentManager;
    protected abstract int getLayoutId();
    protected void initData() {}
    protected void initView() {}
    protected void initListener() {}

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshByBus(AwBaseEvent type) {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (AwBaseActivity) context;
        mFragmentManager = mActivity.getMyFragmentManager();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        EventBus.getDefault().unregister(this);
        super.onDetach();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();
        mCompositeSubscription = new CompositeDisposable();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutId(), container, false);
        initView();
        initData();
        initListener();
        view.setClickable(true);// 防止点击穿透，底层的fragment响应上层点击触摸事件
        return view;
    }

    protected void dismissDialog() {
        if(mActivity == null) {
            return;
        }
        mActivity.dismissDialog();
    }

    @Override
    public void showLoadingDialog() {
        if(mActivity == null) {
            return;
        }
        mActivity.showLoadingDialog();
    }

    @Override
    public void dismissLoadingDialog() {
        if(mActivity == null) {
            return;
        }
        mActivity.dismissLoadingDialog();
    }

    public void showDialogToFinish(String msg) {
        if(mActivity == null) {
            showMsg(msg);
            return;
        }
        mActivity.showDialogToFinish(msg);
    }

    protected void showDialogToBack(String msg) {
        if(mActivity == null) {
            showMsg(msg);
            return;
        }
        mActivity.showDialogToBack(msg);
    }

    public void showDialog(String msg) {
        if(mActivity == null) {
            showMsg(msg);
            return;
        }
        mActivity.showDialog(msg);
    }

    public void showDialog(String msg, View.OnClickListener listener) {
        if(mActivity == null) {
            showMsg(msg);
            return;
        }
        mActivity.showDialog(msg, listener);
    }

    public void showDialogWithCancelDismiss(String msg, View.OnClickListener confirmListener) {
        if(mActivity == null) {
            showMsg(msg);
            return;
        }
        mActivity.showDialogWithCancelDismiss(msg, confirmListener);
    }

    public void showDialogWithCancelFinish(String msg, View.OnClickListener confirmListener) {
        if(mActivity == null) {
            showMsg(msg);
            return;
        }
        mActivity.showDialogWithCancelFinish(msg, confirmListener);
    }

    public void showDialogCustomLeftAndRight(String msg, String leftTxt, String rightTxt, View.OnClickListener leftListener, View.OnClickListener rightListener) {
        if(mActivity == null) {
            return;
        }
        mActivity.showDialogCustomLeftAndRight(msg, leftTxt, rightTxt, leftListener, rightListener);
    }

    public void showInputDialog(String title, String hintMsg, boolean showCancelBtn, AwViewDialog.InputCallback callback) {
        if(mActivity == null) {
            return;
        }
        mActivity.showInputDialog(title, hintMsg, showCancelBtn, callback);
    }

    public void showCommonCustomDialog(String msg, String leftTxt, String rightTxt, boolean showTopImg, boolean showCancelBtn, final View.OnClickListener leftListener, final View.OnClickListener rightListener) {
        if(mActivity == null) {
            return;
        }
        mActivity.showCommonCustomDialog(msg, leftTxt, rightTxt, showTopImg, showCancelBtn, leftListener, rightListener);
    }

    public void showCommonCustomDialog(String title, String msg, String leftTxt, String rightTxt, boolean showTopImg, boolean showCancelBtn, boolean allowCancelOnTouchOutside, final View.OnClickListener leftListener, final View.OnClickListener rightListener) {
        mActivity.showCommonCustomDialog(title, msg, leftTxt, rightTxt, showTopImg, showCancelBtn, allowCancelOnTouchOutside, leftListener, rightListener);
    }

    //========================APP定制部分===================================

    public void showErrorDialog(String msg, View.OnClickListener closeListener) {
        if(mActivity == null) {
            showMsg(msg);
            return;
        }
        mActivity.showErrorDialog(msg, closeListener);
    }
    //========================APP定制部分结束================================

    @Override
    public void showMsg(String msg) {
        if(mActivity == null) {
            AwToastUtil.showShort(AwBaseApplication.getInstance(), msg);
            return;
        }
        mActivity.showMsg(msg);
    }

    public void showMsg(int msgId) {
        if(mActivity == null) {
            AwToastUtil.showShort(AwBaseApplication.getInstance(), msgId);
            return;
        }
        mActivity.showMsg(msgId);
    }

    public void showMsg(final String msg, final String defaultMsg) {
        if(mActivity == null) {
            AwToastUtil.showShort(AwBaseApplication.getInstance(), msg);
            return;
        }
        mActivity.showMsg(msg, defaultMsg);
    }

    protected void setText(TextView tv, String content) {
        if(mActivity == null) {
            if(tv != null) {
                tv.setText(content);
            }
            return;
        }
        mActivity.setText(tv, content);
    }

    protected void showView(View v, boolean show) {
        if(mActivity == null) {
            if(v != null) {
                v.setVisibility(show ? View.VISIBLE : View.GONE);
            }
            return;
        }
        mActivity.showView(v, show);
    }

    protected void setToolbar(String title, AwViewCustomToolbar.OnLeftClickListener leftClickListener) {
        mToolbar = (AwViewCustomToolbar) view.findViewById(R.id.toolbar_custom);
        if(mToolbar != null) {
            mToolbar.hideRightView();//一般很少有页面有右侧, 在需要的时候单独加代码显示, 这里统一隐藏
            mToolbar.setLeftImg(R.drawable.icon_back);
            if(leftClickListener == null) {
                mToolbar.setOnLeftClickListener(new AwViewCustomToolbar.OnLeftClickListener() {
                    @Override
                    public void onLeftTextClick() {
                        fragmentToBack();
                    }
                });
            } else {
                mToolbar.setOnLeftClickListener(leftClickListener);
            }
            if(!AwDataUtil.isEmpty(title)) {
                mToolbar.setToolbarTitle(title);
            } else {
                mToolbar.hideTitleView();
            }
        }
    }

    protected void showToDevMsg() {
        if(mActivity == null) {
            return;
        }
        mActivity.showToDevMsg();
    }

    protected void setToolbarWithBackImg(String title, AwViewCustomToolbar.OnLeftClickListener leftClickListener) {
        setToolbar(title, leftClickListener);
        if(mToolbar != null) {
            mToolbar.setLeftImg(R.drawable.icon_back);
            mToolbar.hideRightView();
        }
    }

    protected void setToolbarHideLeftAndRight(String title, AwViewCustomToolbar.OnLeftClickListener leftClickListener) {
        setToolbar(title, leftClickListener);
        if(mToolbar != null) {
            mToolbar.hideLeftView();
            mToolbar.hideRightView();
        }
    }

    protected void setToolbarHideLeftWithRightImg(String title, int viewId, AwViewCustomToolbar.OnRightClickListener rightClickListener) {
        setToolbar(title, null);
        if(mToolbar != null) {
            mToolbar.hideLeftView();
            mToolbar.showRightView();
            mToolbar.setRightImg(viewId);
            mToolbar.setOnRightClickListener(rightClickListener);
        }
    }

    /**
     * 跳转activity
     *
     * @param clazz
     * @param params 传值格式  key,value
     */
    public void toClass(Class clazz, boolean needFinish, Object... params) {
        if(mActivity == null) {
            return;
        }
        mActivity.toClass(clazz, needFinish, params);
    }

    /**
     * 跳转activity(不传参)
     *
     * @param clazz
     */
    public void toClass(Class clazz, boolean needFinish) {
        if(mActivity == null) {
            return;
        }
        mActivity.toClass(clazz, needFinish);
    }

    public void toClassForResult(Class clazz, int requestCode) {
        if(mActivity == null) {
            return;
        }
        mActivity.toClassForResult(clazz, requestCode);
    }

    /**
     * 跳转fragment
     *
     * @param params 传值格式  key,value
     */
    public void toClass(int viewId, Fragment fragment, boolean addBackStack, Object... params) {
        if(mActivity == null) {
            return;
        }
        mActivity.toClass(viewId, fragment, addBackStack, params);
    }

    /**
     * 跳转fragment
     *
     * @param params 传值格式  key,value
     */
    public void toClassChild(int viewId, Fragment fragment, boolean addBackStack, Object... params) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        boolean isTagNull = null == getChildFragmentManager().findFragmentByTag(fragment.getClass().getName());
        AwLog.d("toClassChild, fragment: " + fragment.getClass().getName() + " ,isAdded: " + fragment.isAdded() + " ,findTag is null?: " + isTagNull);
        if(!fragment.isAdded() && null == getChildFragmentManager().findFragmentByTag(fragment.getClass().getName())) {
            getChildFragmentManager().executePendingTransactions();
            if(params != null) {
                try {
                    fragment.setArguments(mActivity.getFragmentBundle(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if(addBackStack) {
                transaction.add(viewId, fragment, fragment.getClass().getName());
                transaction.addToBackStack(fragment.getClass().getName());
            } else {
                transaction.replace(viewId, fragment, fragment.getClass().getName());
            }
            transaction.commitAllowingStateLoss();
        } else {
            AwLog.d("toClassChild, fragment: " + fragment.getClass().getName() + " 已经存在, 直接展示出来");
            transaction.show(fragment).commitAllowingStateLoss();
        }
    }

    /**
     * 跳转fragment(不传参)
     *
     */
    public void toClass(int viewId, Fragment fragment, boolean addBackStack) {
        if(mActivity == null) {
            return;
        }
        mActivity.toClass(viewId, fragment, addBackStack, new Object[0]);
    }

    public void fragmentToBack() {
        if(mActivity == null) {
            return;
        }
        mActivity.fragmentToBack();
    }

    public void popAllToBack() {
        if(mActivity == null) {
            return;
        }
        mActivity.popAllToBack();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
